#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:

    ListNode* reverselist(ListNode* star) {
        ListNode* pre = nullptr;
        ListNode* cur = star;
        while (cur) {
            ListNode* t = cur->next;
            cur->next = pre;
            pre = cur;
            cur = t;
        }
        return pre;
    }
    ListNode* reverseKGroup(ListNode* head, int k) {
        if (k == 1)return head;
        ListNode* cur = head;

        ListNode* hh = new ListNode(-1);
        hh->next = head;
        ListNode* pre = hh;
        while (cur) {
            ListNode* star = cur;
            ListNode* end = cur;
            int cnt = 1;
            while (end && cnt < k) {
                end = end->next;
                if (end)cnt++;
            }
            if (cnt == k) {
                ListNode* endne = nullptr;
                if (end)endne = end->next;
                if (end)end->next = nullptr;
                ListNode* ss = reverselist(star);
                pre->next = ss;
                star->next = endne;
                pre = star;
                cur = endne;
            }
            else {
                break;
            }
        }
        return hh->next;
    }
};